package com.qkbb.admin.kuibu.qkbb.funcation;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.widget.ImageView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.download.ImageDownloader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.qkbb.admin.kuibu.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;
import java.util.Map;

public class ImageDownloadSDCardCacheHelper {
	public final String TAG = "ImageDownloadSDCardCacheHelper";
	public Map<String, SoftReference<Bitmap>> softCaches = new LinkedHashMap<String, SoftReference<Bitmap>>();
	public LruCache<String, Bitmap> lruCache = null;
    public boolean flage;
    private String imageUrl;

    // 异步加载图片方法
	public void myDownloadImageSDCardCache(final Context context, final String url,
			final ImageView imageView, final String imagename) {
        com.qkbb.admin.kuibu.qkbb.imageloader.ImageLoader imageLoader=com.qkbb.admin.kuibu.qkbb.imageloader.ImageLoader.getInstance(context);
        imageLoader.loadImage(imagename,url,imageView,false);
        imageLoader.setOnImageDownloadListener(new com.qkbb.admin.kuibu.qkbb.imageloader.ImageLoader.OnImageDownloadedListener() {
            @Override
            public void onImageloaded(Bitmap b, ImageView imageView) {
                Log.d("tag", "下载成功");

                imageView.setImageBitmap(b);
                Log.d("tag", "设置成功");
            }

            @Override
            public void onDowndloadFailure(int type) {

            }
        });


//		Bitmap bitmap = null;
//		String filename=SDCardHelper.getInstance().getSDCardBasePath() + File.separator + "keeboo"+ File.separator+imagename;
//        File file=new File(filename);
//        flage=file.exists();
//        RequestQueue requestQueue= Volley.newRequestQueue(context);
//        com.android.volley.toolbox.ImageLoader imageLoader=new com.android.volley.toolbox.ImageLoader(requestQueue, new com.android.volley.toolbox.ImageLoader.ImageCache() {
//            @Override
//            public Bitmap getBitmap(String s) {
//                return null;
//            }
//
//            @Override
//            public void putBitmap(String s, Bitmap bitmap) {
//
//            }
//        });
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
//                .threadPoolSize(4)
//                .writeDebugLogs() // Remove for release app
//                .threadPriority(Thread.NORM_PRIORITY - 2)
//                .build();
//        ImageLoader.getInstance().init(config);
////		bitmap=SDCardHelper.getInstance().loadBitmapFromSDCard(filename);
//        DisplayImageOptions options;
//        options = new DisplayImageOptions.Builder()
//                .showImageOnLoading(R.drawable.check_selector) //设置图片在下载期间显示的图片
//                .showImageForEmptyUri(R.drawable.check_selector)//设置图片Uri为空或是错误的时候显示的图片
//                .showImageOnFail(R.drawable.check_selector)
//                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
//                .cacheOnDisk(true)
//                .considerExifParams(true)
//                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
//                .build();
//        if (flage) {
//            imageUrl = ImageDownloader.Scheme.FILE.wrap(filename);
//        }else {
//            imageUrl=url;
//        }
//        ImageLoader.getInstance().loadImage(imageUrl, new ImageLoadingListener() {
//            @Override
//            public void onLoadingStarted(String s, View view) {
//
//            }
//
//            @Override
//            public void onLoadingFailed(String s, View view, FailReason failReason) {
//
//            }
//
//            @Override
//            public void onLoadingComplete(String s, View view, final Bitmap bitmap) {
//                if (flage){
//                    Log.e("imagename本地", imagename);
//                    imageView.setImageBitmap(bitmap);
//                }else {
//                    Log.e("imagename网络", imagename);
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            imageView.setImageBitmap(bitmap);
//                        }
//                    });
//                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
//                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
//                    byte[] byteArray = stream.toByteArray();
//                    SDCardHelper.getInstance().saveFileToSDCardCustomDir(byteArray, "keeboo", imagename);
//                }
//            }
//
//            @Override
//            public void onLoadingCancelled(String s, View view) {
//
//            }
//        });
//			if (bitmap != null) {
//				Log.e("imagename本地", imagename);
//				imageView.setImageBitmap(bitmap);
//			} else {
//				new MyAsyncTask(context, url, imageView,imagename)
//						.execute(url);
//			}
		}
    public void myDownloadImageSDCardCache(Context context, String url,
                                           ImageView imageView,String imagename,int i) {

//        com.qkbb.admin.kuibu.qkbb.imageloader.ImageLoader imageLoader=com.qkbb.admin.kuibu.qkbb.imageloader.ImageLoader.getInstance(context);
//        imageLoader.loadImage(imagename,url,imageView,false);
//        imageLoader.setOnImageDownloadListener(new com.qkbb.admin.kuibu.qkbb.imageloader.ImageLoader.OnImageDownloadedListener() {
//            @Override
//            public void onImageloaded(Bitmap b, ImageView imageView) {
//                Log.d("tag", "下载成功");
//                Bitmap bitmap=toRoundBitmap(b);
//                imageView.setImageBitmap(toRoundBitmap(bitmap));
//                Log.d("tag", "设置成功");
//            }
//
//            @Override
//            public void onDowndloadFailure(int type) {
//
//            }
//        });

        flage=true;
        Bitmap bitmap = null;
        String filename=SDCardHelper.getInstance().getSDCardBasePath() + File.separator + "keeboo"+ File.separator+imagename;
        bitmap=SDCardHelper.loadBitmapFromSDCard(filename);


        if (bitmap != null) {
            Log.e("bitmap",bitmap.getByteCount()+"");
            Bitmap roundbitmap=toRoundBitmap(bitmap);
            Log.e("roundbitmap",roundbitmap.getByteCount()+"");
            Log.e("imagename本地", imagename);
            imageView.setImageBitmap(roundbitmap);
        } else {
            new MyAsyncTask(context, url, imageView,imagename,flage)
                    .execute(url);
        }
    }
    /**
     * 转换图片成圆形
     * @param bitmap 传入Bitmap对象
     * @return
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }
        Bitmap output = Bitmap.createBitmap(width,
                height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
        final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
        final RectF rectF = new RectF(dst);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }
	}

// 异步任务类
class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
    public Context context;
    public ImageView mImageView;
    public String url;
    public String imageName;
    public Boolean flage;

    public MyAsyncTask(Context context, String url, ImageView mImageView,
            String imageName ) {
        this.context = context;
        this.url = url;
        this.mImageView = mImageView;
        this.imageName=imageName;
    }
    public MyAsyncTask(Context context, String url, ImageView mImageView,
                       String imageName ,boolean flage) {
        this.context = context;
        this.url = url;
        this.mImageView = mImageView;
        this.imageName=imageName;
        this.flage=flage;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap bm = null;
        String urlString = params[0];
        byte b[]= HttpURLConnHelper.loadByteFromURL(urlString,context);
        if (b!=null){
            Log.e("b.lenth", b.length + "");
            Log.e("网络", imageName);
            if (b.length>1024*1024){
                bm=BitmapHelper.createThumbnail(b,20,20);
            }else {
            bm= BitmapFactory.decodeByteArray(b, 0, b.length);
            }
            Log.e("bm.lenth",b.length+"");
            SDCardHelper.getInstance().saveFileToSDCardCustomDir(b, "keeboo", imageName);
            Log.e("flage",new ImageDownloadSDCardCacheHelper().flage+"");
            if (flage!=null){
                return new ImageDownloadSDCardCacheHelper().toRoundBitmap(bm);
            }
            return bm;

        }
//			try {
//				String urlString = params[0];
//				URL urlObj = new URL(urlString);
//				HttpURLConnection httpConn = (HttpURLConnection) urlObj
//						.openConnection();
//				httpConn.setDoInput(true);
//				httpConn.setRequestMethod("GET");
//				httpConn.connect();
//				if (httpConn.getResponseCode() == 200) {
//					InputStream is = httpConn.getInputStream();
//					bm = BitmapFactory.decodeStream(is);
//				}
//				if (bm != null) {
//					String imageName = getImageName(urlString);
//					boolean flag = SDCardHelper
//							.getInstance().saveBitmapToSDCardPrivateCacheDir(
//									bm, imageName, context);
//					Log.e("flag",flag+"");
//					return bm;
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        mImageView.setImageBitmap(result);

    }

}






